using System.Collections;
using UnityEngine;
using SomniumSpace.Bridge;
using SomniumSpace.Bridge.Player;
using SomniumSpace.Bridge.Network;
using SomniumSpace.Bridge.Components;

namespace SomniumSpace.World.UFMTESTING1
{
    /// <summary>
    /// On local player join: triggers an animation on a controlled object,
    /// waits _holdDuration seconds, then disables a target GameObject
    /// (e.g. the welcome box/overlay sitting on top of world spawn).
    ///
    /// Attach this to an empty GameObject that lives in your scene (NOT
    /// generated at runtime). Assign _roomAnimator and _objectToDisable
    /// in the Inspector.
    /// </summary>
    public class WelcomeRoomSequence : MonoBehaviour
    {
        [Header("Animation")]
        [Tooltip("Animator on the object you want to play during the room sequence.")]
        [SerializeField] private Animator _roomAnimator;
        [SerializeField] private string _animationTrigger = "Play";
        [Tooltip("Optional delay after join before the animation starts.")]
        [SerializeField] private float _animationStartDelay = 0f;

        [Header("Timing")]
        [Tooltip("How long to wait before disabling _objectToDisable.")]
        [SerializeField] private float _holdDuration = 5f;

        [Header("Disable On Finish")]
        [Tooltip("GameObject to disable once _holdDuration has elapsed.")]
        [SerializeField] private GameObject _objectToDisable;

        private bool _started;

        private void OnEnable()
        {
            SomniumBridge.PlayersContainer.OnLocalPlayerAdded += HandleLocalPlayerAdded;

            // Covers the case where the local player already joined before
            // this object was enabled (e.g. it's spawned/enabled after join).
            ISomniumPlayer existing = SomniumBridge.PlayersContainer.LocalPlayer;
            if (existing != null)
                HandleLocalPlayerAdded(existing);
        }

        private void OnDisable()
        {
            SomniumBridge.PlayersContainer.OnLocalPlayerAdded -= HandleLocalPlayerAdded;
        }

        private void HandleLocalPlayerAdded(ISomniumPlayer player)
        {
            if (_started)
                return;

            _started = true;
            StartCoroutine(RunSequence(player));
        }

        private IEnumerator RunSequence(ISomniumPlayer player)
        {
            if (_animationStartDelay > 0f)
                yield return new WaitForSeconds(_animationStartDelay);

            if (_roomAnimator != null)
                _roomAnimator.SetTrigger(_animationTrigger);

            yield return new WaitForSeconds(_holdDuration);

            if (_objectToDisable != null)
                _objectToDisable.SetActive(false);
        }
    }
}